package com.xiaoniu.douyinvideo.page

import android.os.Bundle
import android.view.View
import android.widget.MediaController
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.FileUtils
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.xiaoniu.douyinvideo.databinding.ActivityVideoBinding
import com.xiaoniu.douyinvideo.util.FileUtil
import com.xiaoniu.douyinvideo.util.LogUtil
import com.xiaoniu.douyinvideo.util.LogUtil.i
import com.xiaoniu.douyinvideo.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.math.roundToInt

/**
 * @author zhaohe
 */
class VideoActivity : AppCompatActivity() {
    private var binding: ActivityVideoBinding? = null

    //判断是否下载成功，播放下载成功的视频，节约流量
    private var isDownloaded = false
    private var downloadedVideoPath = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        binding = ActivityVideoBinding.inflate(getLayoutInflater())

        setContentView(binding!!.getRoot())

        downloadedVideoPath = intent.getStringExtra("download_url") ?: ""
        val videoUrl = intent.getStringExtra("video_url")
        startDownload(videoUrl)
        ViewCompat.setOnApplyWindowInsetsListener(binding!!.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(0, systemBars.top, 0, 0)
            insets
        }

        binding?.ivBack?.setOnClickListener {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        playVideo()
    }

    private fun playVideo() {
        if (!isDownloaded || downloadedVideoPath.isEmpty()) return
//        val videoUrl = intent.getStringExtra("video_url")
        i("视频播放页开始播放：$downloadedVideoPath")
        // 播放网络视频（示例 URL）
        binding?.videoView?.setVideoURI(downloadedVideoPath.toUri())
        // 添加播放控制器（暂停、播放、进度条）
        val controller = MediaController(this)
        controller.setAnchorView(binding?.videoView)
        binding?.videoView?.setMediaController(controller)
        // 开始播放
        binding?.videoView?.start()
    }

    /**
     * 开始下载
     *
     * @param finalVideoUrl
     */
    private fun startDownload(finalVideoUrl: String?) {
        LogUtil.i("开始进行下载: $finalVideoUrl")

        updateProgress(0)

        val internalMoviesPath = downloadedVideoPath
        i("视频下载路径：$internalMoviesPath")

        val localVideoFile = File(internalMoviesPath)
        if (localVideoFile.exists() && localVideoFile.length() > 0) {
            downloadedVideoPath = internalMoviesPath
            updateProgress(100)
            return
        }

        FileDownloader.setup(this)
        FileDownloader.getImpl().create(finalVideoUrl)
            .setPath(internalMoviesPath)
            .setListener(object : FileDownloadListener() {
                override fun pending(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                }

                override fun started(task: BaseDownloadTask?) {
                    super.started(task)
                    i("视频开始下载")
                }

                override fun connected(
                    task: BaseDownloadTask?,
                    etag: String?,
                    isContinue: Boolean,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {
                    i("视频开始连接")
                }

                override fun progress(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                    val progress = (1f * soFarBytes / totalBytes * 100f).roundToInt()
                    i("视频下载进度：$progress%")
                    updateProgress(progress, false)
                }

                override fun blockComplete(task: BaseDownloadTask?) {
                }

                override fun retry(
                    task: BaseDownloadTask?,
                    ex: Throwable?,
                    retryingTimes: Int,
                    soFarBytes: Int
                ) {
                }

                override fun completed(task: BaseDownloadTask) {
                    i("视频下载完成: ${task.getPath()}")
                    downloadedVideoPath = task.getPath()
                    updateProgress(100)
                }

                override fun paused(task: BaseDownloadTask?, soFarBytes: Int, totalBytes: Int) {
                    i("视频下载暂停")
                }

                override fun error(task: BaseDownloadTask?, e: Throwable) {
                    e.printStackTrace()
                    i("视频下载出错")
                    "视频下载出错".toast()
                }

                override fun warn(task: BaseDownloadTask?) {
                }
            }).start()
    }

    /**
     * 刷新进度
     */
    private fun updateProgress(progress: Int, copyToAlbum: Boolean = true) {
        if (progress == 0) {
            binding?.tvProgress?.text = "开始下载..."
            binding?.pbProgress?.progress = 0
        } else if (progress == 100 && copyToAlbum) {
            isDownloaded = true
            playVideo()
            binding?.llProgress?.visibility = View.GONE
            videoToAlbum()
        } else if (binding?.pbProgress?.progress != progress) {
            binding?.pbProgress?.progress = progress
            binding?.tvProgress?.text = "$progress%"
        }
    }

    /**
     * 视频显示在相册中
     */
    private fun videoToAlbum() {
        try {
            val uri = FileUtil.createMediaFile(
                application,
                EncryptUtils.encryptMD5ToString(downloadedVideoPath) + ".mp4"
            )
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    FileUtil.writeToMediaFile(application, downloadedVideoPath, uri)
                }
                "视频下载完成".toast()
            }
            FileUtils.notifySystemToScan(uri.getPath())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}